<?php
namespace Manage\Model;
use Think\Model;
use Common\Library\Category;
class ArticleCategoryModel extends Model{
	/**
	 * 添加或修改
	 */
	private $DescriptionModel;
	function _initialize(){
		parent::_initialize();
		$this->DescriptionModel=M('ArticleCategoryDescription');
	}
	public function operArticleCategory($data,$article_category_id=0){
		$cate_data=$this->data($data)->create();
		$cate_data['date_modified']=time();
		if($article_category_id){		
			$this->where(array('article_category_id'=>$article_category_id))->save($cate_data);
		}else{
			$cate_data['date_added']=time();
			$article_category_id=$this->add($cate_data);
		}
		
		$map['article_category_id']=$article_category_id;
		$this->DescriptionModel->where($map)->delete();
		foreach ($data['article_category_description'] as $language_id => $article_category_description) {
			$article_category_description['language_id']=$language_id;
			$article_category_description['article_category_id']=$article_category_id;
			$this->DescriptionModel->data($article_category_description)->add();
		}
	}
	public function getArticleCategory($article_category_id){
		$map=array('article_category_id'=>(int)$article_category_id);
		$article_category=$this->where($map)->find();
		$acd=$this->DescriptionModel->where($map)->select();
		foreach ($acd as $v) {
			$article_category['article_category_description'][$v['language_id']]=$v;
		}
		return $article_category;
	}
	/**
	 * 获取分类列表
	 */
	public function getArticleCategories($data=array()){
		$map=array(
			'language_id'	=>	get_default_lng_id()
			);
		$order='sort_order '. (isset($data['order'])?$data['order']:'ASC');
		$order .= ',article_category_id DESC';
		if(isset($data['article_category_id'])) $map[C('DB_PREFIX').'article_category.article_category_id']=array('neq',$data['article_category_id']);
		if(isset($data['status'])) $map['status']=$data['status'];
		if(isset($data['title'])) $map['title'] = array('like',"%".$data['title']."%");
		$article_categories=$this->join('LEFT JOIN  __ARTICLE_CATEGORY_DESCRIPTION__ ON __ARTICLE_CATEGORY__.article_category_id=__ARTICLE_CATEGORY_DESCRIPTION__.article_category_id')->where($map)->field(C('DB_PREFIX')."article_category.article_category_id,title,parent_id,image,status,sort_order")->order($order)->select();
		return $article_categories;
	}
	public function getChildId($article_category_id){
		$cate=$this->select();
		$cate_ids=Category::getChildsId ($cate, $article_category_id,"article_category_id","parent_id");
		$cate_ids=array_merge(array($article_category_id),$cate_ids);		
		return $cate_ids;
	}
		
	public function del($article_category_id){
		$return=0;
		$map['article_category_id']=array('in',$this->getChildId($article_category_id));
		$return=$this->where($map)->delete();
		$this->DescriptionModel->where($map)->delete();
		return $return;
	}
}